// $.getScript("/Portal/test/js/khjd.js");

$(function () {

    //用于debugger alert()
    var originAlert = window.alert; // 首先记录原生的alert
    window.alert = function (text) { // 用我们带断点的alert覆盖window.alert
        // debugger;
        return originAlert.call(window, text);
    };

    console.log("开始加载自定义。。。。");
    $(".myblock").css({
        "padding-bottom": "15px"
    })
    $(".mylabel").css({
        "font-weight": "bold",
        "font-size": "13px",
        "border-bottom": "2px solid #ccc",
        "height": "22px",
        "width": "96%"
    });

    // 模块标签点击
    $(".mylabel").click(function () {
        var that = $(this);
        var fa_right = "fa fa-chevron-right";
        var fa_down = "fa fa-chevron-down";
        var $next = that.next();
        //展开
        if (that.hasClass(fa_right)) {
            that.removeClass(fa_right);
            that.addClass(fa_down);
            $next.hide();
            console.log("go r");
        } else {
            that.removeClass(fa_down);
            that.addClass(fa_right);
            $next.show();
            // console.log("go l");
        }
    });


    //初始化js
    if (window.addEventListener) {
        window.addEventListener("load", csh, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", csh);
    } else {
        window.onload = csh;
    }


});

//初始化
function csh() {
    //币别
    // curChange();
    // 初始化子表地址编码 dropdownlist 映射
    dizi_drop_list();
    // 设置语言
    setLanguage();
    //销售代表
    queryXsdb();
    //地址编码
    // BPADDRESSCHGInit();
    //默认收获地址
    checboxOnlyDefshflgInit();

    inputKeypress();


}


//付款条件编码：现金交易
var xjbm = "00001";

//提交时表单验证的可变数据
var thisValidData = [];


// 收获地址默认控制
function checboxOnlyDefshflg($this) {

    var rowIndex = $this.parents("tr").data("row");
    var thisvals = $this.SheetComment().GetValue();
    var rowField = $this.SheetComment().DataField;
    var tbField = rowField.split('.')[0];
    var rowSibField = rowField.substr(0, rowField.indexOf("_XS"));
    var rowcount = $.MvcSheetUI.GetElement(tbField).SheetGridView().RowCount;

    if (!thisvals && rowcount > 0) {
        for (var i = 1; i < rowcount + 1; i++) {
            var shflg = $.MvcSheetUI.GetControlValue("BPADDRESSCHG.YSHFLG_XS", i);
            if (shflg) {
                $.MvcSheetUI.SetControlValue(rowField, true, i);
                $.MvcSheetUI.SetControlValue(rowSibField, 2, i);
                break;
            }
        }
        return false;
    }

    for (var i = 1; i < rowcount + 1; i++) {
        // debugger;
        if (rowIndex != i) {
            $.MvcSheetUI.SetControlValue(rowField, false, i);
            $.MvcSheetUI.SetControlValue(rowSibField, 1, i);
        }else{
            $.MvcSheetUI.SetControlValue(rowSibField, 2, i);
        }
    }
}

function checboxOnlyDefshflgInit() {

    var tb = $.MvcSheetUI.GetElement("BPADDRESSCHG").SheetGridView();
    var rowcount = tb.RowCount;

    for (var i = 1; i < rowcount + 1; i++) {
        // debugger;
        if ($.MvcSheetUI.GetControlValue("BPADDRESSCHG.YSHFLG_XS", i)) {
            $.MvcSheetUI.GetElement("BPADDRESSCHG.YDEFSHFLG_XS", i).removeAttr("disabled");
        }
    }

}


function checboxOnly($this) {

    var rowIndex = $this.parents("tr").data("row");
    var thisvals = $this.SheetComment().GetValue();
    var rowField = $this.SheetComment().DataField;
    var tbField = rowField.split('.')[0];
    var rowSibField = rowField.substr(0, rowField.indexOf("_XS"));

    var rowcount = $.MvcSheetUI.GetElement(tbField).SheetGridView().RowCount;


    if (!thisvals && rowcount > 0) {
        $.MvcSheetUI.GetElement(rowField, 1).SheetComment().SetValue(true);
        $.MvcSheetUI.GetElement(rowSibField, 1).SheetComment().SetValue(2);

        return false;
    }

    for (var i = 1; i < rowcount + 1; i++) {
        // debugger;
        if (rowIndex != i) {

            $.MvcSheetUI.GetElement(rowField, i).SheetComment().SetValue(false);
            $.MvcSheetUI.GetElement(rowSibField, i).SheetComment().SetValue(1);
        }else{
            $.MvcSheetUI.GetElement(rowSibField, i).SheetComment().SetValue(2);
        }
    }
}

//是否收获地址 chcekbox
function isReceivingAdd_Chcekbox($this) {
    var vals = $this.SheetComment().GetValue();
    var rowIndex = $this.parents("tr").data("row");
    //是否默认收货地点
    var $daulRecei = $.MvcSheetUI.GetElement("BPADDRESSCHG.YDEFSHFLG_XS", rowIndex);

    var $sib = $.MvcSheetUI.GetElement($this.SheetComment().DataField.substr(0, $this.SheetComment().DataField.indexOf("_XS")), rowIndex);
    // 1否2是，是收获地址
    if (vals) {
        //设置为是并解除 disable
        $daulRecei.SheetRadioButtonList().SetValue(2);
        $daulRecei.removeAttr("disabled");
        $daulRecei.change();

        $sib.SheetComment().SetValue(2);


    } else {
        //设置为否和disable
        $daulRecei.SheetRadioButtonList().SetValue(1);
        $daulRecei.attr("disabled", "disabled");

        $sib.SheetComment().SetValue(1);

    }
}


//是否收获地址 raido 类型的--不用了
function isReceivingAdd($this) {
    var vals = $this.SheetComment().GetValue();
    var rowIndex = $this.parents("tr").data("row");
    //是否默认收货地点
    var $daulRecei = $.MvcSheetUI.GetElement("BPADDRESSCHG.YDEFSHFLG", rowIndex);
    //装运地
    var $stofcy = $.MvcSheetUI.GetElement("BPADDRESSCHG.STOFCY_XS", rowIndex);

    // 1否2是，是收获地址
    if (vals && vals == 2) {
        //设置为是并解除 disable
        $daulRecei.SheetRadioButtonList().SetValue(2);
        $daulRecei.removeAttr("disabled");
        $daulRecei.change();
        // 装运地必填
        $stofcy.SheetComment().Required = true;
        if (!$stofcy.SheetComment().GetValue())
            $stofcy.SheetComment().AddInvalidText($stofcy, "*", false);
        $stofcy.blur(function () {
            var $thisblur = $(this);
            if ($thisblur.SheetComment().GetValue()) {
                $thisblur.SheetComment().RemoveInvalidText($thisblur);
            } else {
                $thisblur.SheetComment().AddInvalidText($thisblur, "*", true);
            }
        })

    } else {
        //设置为否和disable
        $daulRecei.SheetRadioButtonList().SetValue(1);
        $daulRecei.attr("disabled", "disabled");
        // 装运地非必填
        $stofcy.SheetComment().Required = true;
        $stofcy.SheetComment().RemoveInvalidText($stofcy);
    }
}

//子表 多行默认行唯一  ---不用了
function sublist_only_one($this, gridViewBm, gridDataBm) {

    var gridView = $.MvcSheetUI.GetElement(gridViewBm).SheetGridView();
    var thisIndex = $this.parents("tr").data("row");

    var thisvals = $.MvcSheetUI.GetElement(gridDataBm, thisIndex).SheetRadioButtonList().GetValue();
    // 值的改变才会触发，当值为1 的时候，说明从2变成1，设置第一行为默认值
    if (thisvals == 1) {
        // $.MvcSheetUI.GetElement(gridDataBm, 1).SheetRadioButtonList().SetValue(2);
        return false;
    }

    var rowCount = gridView.RowCount;
    for (var i = 1; i < rowCount + 1; i++) {
        // debugger;
        $.MvcSheetUI.GetElement(gridDataBm, i).SheetRadioButtonList().SetValue(1);
    }

    $.MvcSheetUI.GetElement(gridDataBm, thisIndex).SheetRadioButtonList().SetValue(2);

}

//地址编码联动
function dizi_drop_list() {
    var di = "BPADDRESSCHG";//客户地址子表
    var dibm = "BPADDRESSCHG.BPAADD";//地址行编码

    var gridView = $.MvcSheetUI.GetElement(di).SheetGridView();

    var rowCount = gridView.RowCount;
    var defaultItems = "";
    for (var i = 1; i < rowCount + 1; i++) {
        defaultItems += $.MvcSheetUI.GetElement(dibm, i).SheetTextBox().GetValue();
        if (rowCount != i) {
            defaultItems += ";";
        }
    }
    di = "CONTACTCHG";//地址联系人子表
    dibm = "CONTACTCHG.BPAADD";//地址联系人行编码

    //给 地址联系人子表 的地址编码 SheetDropDownList 赋 默认值
    renderDefaultItems(di, dibm, defaultItems);
}

//重新渲染子表赋值
function renderDefaultItems(di, dibm, defaultItems) {
    var gridView = $.MvcSheetUI.GetElement(di).SheetGridView();
    var templateSelect = gridView.template.find("td>select[data-field='" + dibm + "']");
    if (templateSelect.data("defaultItems") != defaultItems) {
        var rowCount = gridView.RowCount;
        //设置 子表 template 里的 SheetDropDownList  defaultItems
        templateSelect.attr("data-defaultItems", defaultItems);

        for (var i = 1; i < rowCount + 1; i++) {
            var vals = $.MvcSheetUI.GetControlValue(dibm, i);
            vals = vals ? vals : $.MvcSheetUI.GetSheetDataItem(dibm, i);
            var $UIManager = $.MvcSheetUI.GetElement(dibm, i).SheetUIManager();
            $UIManager.SetEmpty();//清空原数据
            $UIManager.DefaultItems = defaultItems; //重新赋值
            $UIManager.Render();//重新渲染

            if (vals && defaultItems.indexOf(vals) != -1) {
                $.MvcSheetUI.SetControlValue(dibm, vals, i);
            }
        }
    }
}

//设置语言
function setLanguage() {

    var languagesMap = {"en": "EN_US", "zh_CN": "ZH_CN", "zh_TW": "ZH_TW"};
    $.MvcSheetUI.SetControlValue("CHANGELANG", languagesMap["zh_CN"]);
    var languVal = $.MvcSheetUI.GetElement("CHANGELANG").SheetComment().GetValue();
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + "/language/get",
        data: {},
        dataType: "json",
        async: true,
        success: function (res) {

            if (res.Success && res.Message && languagesMap[res.Message] != languVal) {
                $.MvcSheetUI.SetControlValue("CHANGELANG", languagesMap[res.Message]);
            }
        }
    });
}


var cnpjValOrig = null;

// 企业经营信息
function loadBUSSTACHG() {

    var vals = $.MvcSheetUI.GetControlValue("YCNPJ");

    if (cnpjValOrig == vals) {
        return false;
    } else {
        cnpjValOrig = vals;
    }

    var gridNew = $.MvcSheetUI.GetElement("BUSSTACHG").SheetGridView();

    if (vals && vals.trim()) {
        console.log("loadBUSSTACHG...");

        var param = '{"YCNPJ":"' + vals + '"}';
        $.ajax({
            url: $.MvcSheetUI.PortalRoot + "/RunBizQuery/GetGridData",
            data: {
                "schemaCode": "ZMANSTATE",
                "queryCode": "queryZMANSTATE",
                "FilterStr": param,
                "PageIndex": 1,
                "PageSize": 20
            },
            dataType: "json",
            async: true,
            success: function (data) {
                if (data) {
                    gridNew._Clear();
                    if (data.Total && data.Total > 0) {
                        for (var i = 0; i < data.Total; i++) {
                            gridNew._AddRow();

                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YEARS", data.Rows[i].YEAR, i + 1);//年份
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YZCZE", data.Rows[i].ZCZE, i + 1);//资产总额
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YQZZE", data.Rows[i].FZZE, i + 1);//负债总额
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YYSZE", data.Rows[i].YYZSR, i + 1);//营业总收入
                            $.MvcSheetUI.SetControlValue("BUSSTACHG.YJLR", data.Rows[i].JLR, i + 1);//净利润
                        }
                    }
                    gridNew._AddRow();
                }

            }
        });

    } else {
        gridNew._Clear();
        gridNew._AddRow();
    }

    return false;
}


function queryXsdb() {
    var loginCode = $.MvcSheetUI.GetControlValue("THISlOGINNAME");

    if (!loginCode) return false;

    var param = '{"ADYHM":"' + loginCode + '"}';
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + "/RunBizQuery/GetGridData",
        data: {
            "schemaCode": "ZXSDBX3",
            "queryCode": "queryXSDBsByLoginCode",
            "FilterStr": param,
            "PageIndex": 1,
            "PageSize": 20
        },
        dataType: "json",
        async: true,
        success: function (data) {
            if (data) {
                if (data.Total && data.Total > 0) {
                    $.MvcSheetUI.SetControlValue("REP_0_XS", data.Rows[0].MC);
                    $.MvcSheetUI.SetControlValue("REP_0", data.Rows[0].BM);
                    queryTjz();
                }
            }
        }
    });
}

function queryTjz() {
    var xsdbbm = $.MvcSheetUI.GetControlValue("REP_0");
    if (!xsdbbm || $.MvcSheetUI.GetControlValue("TSCCOD_0_XS")) return false;

    var param = '{"BM":"' + xsdbbm + '"}';
    $.ajax({
        url: $.MvcSheetUI.PortalRoot + "/RunBizQuery/GetGridData",
        data: {
            "schemaCode": "ZKHTJZX31",
            "queryCode": "ZKHTJZX31",
            "FilterStr": param,
            "PageIndex": 1,
            "PageSize": 20
        },
        dataType: "json",
        async: true,
        success: function (data) {
            if (data) {
                if (data.Total && data.Total > 0) {
                    $.MvcSheetUI.SetControlValue("TSCCOD_0_XS", data.Rows[0].KHTJZ1);
                    $.MvcSheetUI.SetControlValue("TSCCOD_1_XS", data.Rows[0].KHTJZ2);
                    $.MvcSheetUI.SetControlValue("TSCCOD_2_XS", data.Rows[0].KHTJZ3);
                    $.MvcSheetUI.SetControlValue("TSCCOD_3_XS", data.Rows[0].KHTJZ4);
                    $.MvcSheetUI.SetControlValue("TSCCOD_4_XS", data.Rows[0].KHTJZ5);
                    $.MvcSheetUI.SetControlValue("TSCCOD_0", data.Rows[0].KHTJZBM1);
                    $.MvcSheetUI.SetControlValue("TSCCOD_1", data.Rows[0].KHTJZBM2);
                    $.MvcSheetUI.SetControlValue("TSCCOD_2", data.Rows[0].KHTJZBM3);
                    $.MvcSheetUI.SetControlValue("TSCCOD_3", data.Rows[0].KHTJZBM4);
                    $.MvcSheetUI.SetControlValue("TSCCOD_4", data.Rows[0].KHTJZBM5);
                }
            }
        }
    });
}


// 客户地址编码自增，最多26 个字母，且表单初始化row 为0；
function insrBPAADD() {
    var $tb = $.MvcSheetUI.GetElement("BPADDRESSCHG").SheetGridView();
    if ($tb) {
        var rowIndex = $tb.RowCount;
        var vals = $.MvcSheetUI.GetControlValue("BPADDRESSCHG.BPAADD", rowIndex);
        if (!vals) {
            $.MvcSheetUI.SetControlValue("BPADDRESSCHG.BPAADD", String.fromCharCode((64 + rowIndex)), rowIndex);
        }
    }
}

function getYbpcbusage() {
    var year0 = new Date().getTime();
    var yregstartd = $.MvcSheetUI.GetControlValue("YREGSTARTD");
    if (yregstartd) {
        var year1 = new Date(yregstartd).getTime();
        var year3 = 0;
        if (year0 > year1) {
            var year3 = (year0 - year1) / (3600 * 1000 * 24 * 365);
            if (year3)
                year3 = year3.toFixed(1);
        }


        $.MvcSheetUI.SetControlValue("YBPCBUSAGE", year3);

    }
}


// 监听 /F7 118/ 回车 13
function inputKeypress() {

    if ($.MvcSheetUI.SheetInfo.ActivityCode != "Activity2") {
        return false;
    }

    // console.log(11);
    $('input[data-popupwindow="PopupWindow"]').parent().bind('keyup', function (event) {

        if (event.keyCode == "13") {
            event.preventDefault();
            //回车执行查询
            var $that = $(event.currentTarget);
            $that.find("a").click();

        }
    });
}

//依赖清空
function dependenceClean(fiel1,fiel2){
    try {
        $.MvcSheetUI.SetControlValue(fiel1,"");
        $.MvcSheetUI.SetControlValue(fiel2,"");
    }catch(e){
        console.log(e);
    }
}



//加载客户
var  removeFeild = ['OBJECTID','NAME','CREATEDBY','CREATEDBYPARENTID','OWNERID','OWNERPARENTID','CREATEDTIME','MODIFIEDBY','MODIFIEDTIME','RUNNINGINSTANCEID'];
var BPRNAM_data_flag = 1;
function loadCustDataChange() {

    if (BPRNAM_data_flag ==1){
        BPRNAM_data_flag =2;
    }else {
        return  false;
    }
    var instanceId = $.MvcSheetUI.GetControlValue("INSTID");

    if(instanceId){
        $.ajax({
            url: window.location.origin + "/sunlord/custFilingDataChange",
            data: {"sInstanceId":instanceId},
            dataType: "json",
            type : "POST",
            async: true,
            success: function (result) {

                if (result && result.code == "0" && result.data) {
                    //主数据
                    if(result.data["BPCCHG"]){
                        var data = result.data["BPCCHG"];
                        delete  data["BPRNAM"];

                        for (var i = 0; i < removeFeild.length; i++) {
                            delete  data[removeFeild[i]];
                        }

                        for (let k in data) {
                            try {
                                if (data[k] instanceof  Array){
                                    setFiles(k,data[k],0);
                                }else{
                                    $.MvcSheetUI.SetControlValue(k,data[k]);
                                }

                            }catch (e) {
                                console.log(k+":"+data[k]);
                                console.log(e);
                            }
                        }
                    }
                    //企业经营状况
                    setItemsData(result.data,"BUSSTACHG");
                    //收获地址
                    setItemsData(result.data,"BPADDRESSCHG");
                    //联系人
                    setItemsData(result.data,"CONTACTCHG");
                    //关联企业
                    setItemsData(result.data,"CRMBPCCHG");
                    //客户产品属性
                    setItemsData(result.data,"CRMBPCITMCHG");
                }else{
                    console.log(result);
                    alert("获取客户建档信息失败");
                }
                BPRNAM_data_flag =1;
            }
        });
    }
    BPRNAM_data_flag =1;

    return  false;

}

function setItemsData(data,feild){
    if(data[feild]){
        var dataArray = data[feild];
        var grid = $.MvcSheetUI.GetElement(feild).SheetComment();
        grid._Clear();
        for (var i = 0; i < dataArray.length; i++) {
            for (var j = 0; j < removeFeild.length; j++) {
                delete  dataArray[i][removeFeild[j]];
            }
            grid._AddRow();
            var rowIndex = i+1;
            for(let k in dataArray[i]){
                try {
                    if (data[k] instanceof  Array) {
                        setFiles(k,dataArray[i][k],i);
                    }else{
                        $.MvcSheetUI.SetControlValue(feild.concat(".").concat(k),dataArray[i][k],rowIndex);
                    }
                }catch (e) {
                    console.log(k+":"+data[k]);
                    console.log(e);
                }
            }
        }

    }
}


function setFiles(feild,data,feildIndex){

    for (var i = 0; i < data.length; ++i) {
        $.MvcSheetUI.GetElement(feild,feildIndex).SheetAttachment()
            .CreateFileElement($.trim(data[i].Code), data[i].Name, data[i].Size, data[i].Url, data[i].ContentType);
    }

}